#!/bin/bash
clean_bottle_cmd="deepin-wine6-stable"

version_gt() { test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" != "$1"; }

CheckTool()
{
    a=$(which $1)
    if [ $? -ne 0 ]
    then
        echo "missing $1, need to install package \"$2\""
        exit
    fi
}
CheckParamE()
{
    if [ -z "$1" ]
    then
        echo "$2"
        exit 1
    fi
}
CheckPathExists()
{
    if [ ! -d "$1" ]
    then
        echo "$2"
        exit 1
    fi
}


Check_icons()
{
    if [ ! -d "icons" ];then
        mkdir -p icons/hicolor/48x48/apps
        mkdir -p icons/hicolor/16x16/apps
        mkdir -p icons/hicolor/64x64/apps
        mkdir -p icons/hicolor/128x128/apps
        mkdir -p icons/hicolor/32x32/apps
    fi
    if [[ -n $(find icons/ -name ${1}.svg) ]];then
        echo "${1}.svg"
    elif [[ -n $(find icons/ -name ${1}.png) ]];then
        echo "${1}.png"
    else
        exit 1
    fi
}

CheckArchEnv()
{
    if [ -n "$enable_package_x86" ]&&[ $enable_package_x86 -eq 1 ] ;then
        if [ -z "$SPECIFY_SHELL_PATH_X86" ]||[ -z "$package_depends_x86" ]||[ -z "$apprun_cmd_x86" ]; then
            echo "<===== 变量SPECIFY_SHELL_PATH_X86 | package_depends_x86 | apprun_cmd_x86 都不能为空！！！"
            exit 1
        fi
        clean_bottle_cmd="$apprun_cmd_x86"
    fi

    if [ -n "$enable_package_arm64" ]&&[ $enable_package_arm64 -eq 1 ] ;then
        if [ -z "$SPECIFY_SHELL_PATH_ARM64" ]||[ -z "$package_depends_arm64" ]||[ -z "$apprun_cmd_arm64" ]; then
            echo "<===== 变量SPECIFY_SHELL_PATH_ARM64 | package_depends_arm64 | apprun_cmd_arm64 都不能为空！！！"
            exit 1
        fi
    fi

    if [ -n "$enable_package_loongarch64" ]&&[ $enable_package_loongarch64 -eq 1 ] ;then
        if [ -z "$SPECIFY_SHELL_PATH_loongarch64" ]||[ -z "$package_depends_loongarch64" ]||[ -z "$apprun_cmd_loongarch64" ]; then
            echo "<===== 变量SPECIFY_SHELL_PATH_loongarch64 | package_depends_loongarch64 | apprun_cmd_loongarch64 都不能为空！！！"
            exit 1
        fi
    fi
}

CheckTool "fakeroot" "fakeroot"

CheckParamE "$app_description" "App description not given"
CheckParamE "$app_name" "App name not given"
CheckParamE "$app_name_zh_cn" "App zh-cn name not given"
#CheckParamE "$desktop_file_categories" "Categories of desktop file not given"
#CheckParamE "$desktop_file_icon" "Icon file of desktop file not given"
#CheckParamE "$desktop_file_main_exe" "Main exe filename not given
#===>Wine set this value to WMClass of app window, Dock/Launcher need this for matching"
CheckParamE "$deb_package_name" "Package name not given"
CheckParamE "$deb_version_string" "Package version not given"
CheckArchEnv


if [[ "$deb_version_string" == *"deepin"* ]];then
    echo "版本号不要用deepin标识，方便区分应用包的来源"
    exit
fi

if [ "$old_package_name" == "$deb_package_name" ];then
    echo "old_package_name 不能和deb_package_name一致"
    exit
fi

if [ -z "$public_bottle_name" ];then
    export public_bottle_name="$deb_package_name"
fi

BottlePath="$HOME/.deepinwine/$public_bottle_name"

export desktop_file_icon=$(Check_icons $deb_package_name)
if [ -n "$desktop_file_categories" ] && [ -z "$desktop_file_icon" ]; then
    if [ -n "$1" ] && [ -d "/opt/apps/$deb_package_name/entries/icons" ]; then
        echo "cp icon from /opt/apps/$deb_package_name/entries/icons"
        iconpath=$(pwd)
        cd "/opt/apps/$deb_package_name/entries/icons"
        find -iname "$deb_package_name"* -exec cp "{}" "$iconpath/icons/{}" \;
        cd -
    else
        echo "make icon form PE file"
        ./mkicons.sh
    fi
fi
export desktop_file_icon=$(Check_icons $deb_package_name)
if [ -n "$desktop_file_categories" ] && [ -z "$desktop_file_icon" ]; then
    echo "没找到图标"
#    exit
fi

#Replace USER value to string
export EXEC_PATH=$(echo "$exec_path" | sed -e "s/$USER/\$USER/g")

if [ -z "$deb_packager" ];then 
   export deb_packager="UOS Team";
fi
if [ -z "$deb_packager_email" ];then deb_packager_email="penghao@linuxdeepin.com";fi
if [ -z "$deb_date" ];then deb_date=`date -R`;fi

echo "+++++ Empire Starts here. +++++"
echo "app description:     $app_description"
echo "app name:            $app_name"
echo "app name zh-cn:      $app_name_zh_cn"
echo "date:                $deb_date"
echo "deb package name:    $deb_package_name"
echo "deb packager:        $deb_packager"
echo "packager email:      $deb_packager_email"
echo "version:             $deb_version_string"
echo "app categories:      $desktop_file_categories"
echo "desktop icon:        $desktop_file_icon"
echo "app main executable: $desktop_file_main_exe"
echo "origin bottle name:  $origin_bottle_name"
echo "public bottle name:  $public_bottle_name"
echo "old package name:    $old_package_name"
echo "package depends:     $package_depends"
echo "mime type:           $mime_type"
echo "activex name:        $activex_name"
echo "bottle path:         $BottlePath"
echo "make autostart:      $make_autostart"
echo "send to desktop:     $send_to_desktop"
echo "exec file path:      $EXEC_PATH"

curdir=`pwd`
stgdir="/tmp/staging.dir"
dstdir="/tmp/final.dir"
outdir="$dstdir/opt/apps/$deb_package_name"
outentries="$outdir/entries"
outfiles="$outdir/files"
run_sh_dir="/opt/apps/$deb_package_name/files"
uos_package_save="$curdir/output/uos"
patch_dll_path=$run_sh_dir/dlls

CheckPathExists "$curdir/debian"            "debian package building scripts lost."
CheckPathExists "$curdir/template"          "package template scripts lost."

echo "=====>Preparing packaging environment..."
if [ -d "$stgdir" ]; then rm -rf "$stgdir"; fi
mkdir -p "$stgdir"
if [ -d "$dstdir" ]; then rm -rf "$dstdir"; fi
mkdir -p "$dstdir"
mkdir -p "$outentries"
mkdir -p "$outfiles"
if [ ! -d "$uos_package_save" ]; then mkdir -p "$uos_package_save"; fi

echo "<=====done."

if [ -n "$USE_PACKAGE_DLLS" ] && [ -d "$patch_dll_path" ];then
    cp -r --preserve=timestamp "$patch_dll_path" "$outfiles/"
    echo "===========copy patch dlls==============="
    ls "$patch_dll_path" -alh
    echo "=========================================="
fi

WIN_FONTS=$(ls "$BottlePath/drive_c/windows/Fonts")
if [ -n "$WIN_FONTS" ];then
    echo ""
    read -p "容器中打包了如下字体: $WIN_FONTS。请确认这些字体没有侵犯版权，否则会有法律风险!"
fi

if [ -d "$curdir/specified/$deb_package_name/root/" ]; then
    echo "copy root files.."
    cp -ruv $curdir/specified/$deb_package_name/root/* "$dstdir"
fi

if [ ! -d "$outfiles/dlls" ];then
    strip "$outfiles/dlls/"*.so
fi

if [ -n "$1" ] && [ -f "/opt/apps/$deb_package_name/files/files.7z" ]; then
    echo "Use last bottle file"
    cp /opt/apps/$deb_package_name/files/files.7z "$outfiles/"
else
    CheckPathExists "$BottlePath" "Original bottle do NOT exist."

    echo "=====>Clean bottle..."
    ./cleanbottle.sh $BottlePath $clean_bottle_cmd
    echo "<=====done."

    echo "=====>Creating program files archive..."
    cp -r $BottlePath/* "$stgdir"
    ./fixbottle.sh "$stgdir" $deb_package_name
    # Dir links in profile should been recreated when deploy.
    find "$stgdir/drive_c/users/$USER" -type l -exec rm "{}" \;

    # remove lnk file
    find "$stgdir/drive_c/" -type f -name "*.lnk" -exec rm "{}" \;
    # specially disable kvipgui.exe
    find "$stgdir/drive_c/" -type f -name "kvipgui.exe" -exec rm "{}" \;

    # Remove packager personal information. We will expand user name when deploy.
    sed -i "s#$USER#@current_user@#" $stgdir/*.reg
    mv "$stgdir/drive_c/users/$USER" "$stgdir/drive_c/users/@current_user@"
    # Merge additional files for this package.
    if [ -d "$curdir/specified/$deb_package_name/bottle" ]; then
        cp -ruv $curdir/specified/$deb_package_name/bottle/* $stgdir
    else
        cp -ruv $curdir/specified/temp/bottle/* $stgdir
    fi

    7z a -t7z "$outfiles/files.7z" "$stgdir/*"
fi

md5sum "$outfiles/files.7z" | awk '{print $1}' > "$outfiles/files.md5sum"

echo "<=====package bottle done."

if [ -n "$enable_package_all" ]&&[ $enable_package_all -eq 1 ] ;then
    ./script-packager-per-arch.sh "$SPECIFY_SHELL_PATH_all" "$package_depends_all" "$apprun_cmd_all" "all"
    echo "<=====create all package done."
    exit
fi

if [ -n "$enable_package_x86" ]&&[ $enable_package_x86 -eq 1 ] ;then
    ./script-packager-per-arch.sh "$SPECIFY_SHELL_PATH_X86" "$package_depends_x86" "$apprun_cmd_x86" "i386"
    echo "<=====create x86 package done."
fi

if [ -n "$enable_package_arm64" ]&&[ $enable_package_arm64 -eq 1 ] ;then
    ./script-packager-per-arch.sh "$SPECIFY_SHELL_PATH_ARM64" "$package_depends_arm64" "$apprun_cmd_arm64" "arm64"
    echo "<=====create arm64 package done."
fi

if [ -n "$enable_package_loongarch64" ]&&[ $enable_package_loongarch64 -eq 1 ] ;then
    ./script-packager-per-arch.sh "$SPECIFY_SHELL_PATH_loongarch64" "$package_depends_loongarch64" "$apprun_cmd_loongarch64" "loongarch64"
    echo "<=====create loongarch64 package done."
fi

exit 0
